var fileType = ($.os.match("Windows")) ? "*.txt;*.csv;": function (f){
  return f instanceof Folder || (f instanceof File && f.fullName.match(/(\.txt|\.csv)$/i));
};
var sourceFile = File.openDialog("Choose a csv file.", fileType);
var datas = readFileLinesToList(sourceFile)

// var widest = 0
// var needReturn = false

if (datas !== null) {
  addDoc();
  var startRect = [-7500, 7700, -7000, 7600]
  var maxPoint = [-7000, 7600]

  moveArtboardToConner(startRect);
  for (var i = 0, len = datas.length; i < len; i++) {
    try {
      putArtboard(datas[i], i);
    } catch (e) {
      alert(e)
    }
    artboards = app.activeDocument.artboards
    artboard = artboards[artboards.getActiveArtboardIndex()]
  }
  app.activeDocument.artboards[0].remove();

  var saveFolder = sourceFile.fullName.split('.')[0] + '/'
  var pathArr = sourceFile.fullName.split('/')
  var fileName = pathArr[pathArr.length - 1].replace('.csv', '.ai')
  saveDoc(saveFolder + fileName)
}

function moveArtboardToConner(rect) {
  artboards = app.activeDocument.artboards
  artboard = artboards[artboards.getActiveArtboardIndex()]
  artboard.artboardRect = rect
}

function addDoc(size) {
  size = size || '500x100'
  var sizes = size.match(/()\d+(\.\d+)?/g)
  if (!sizes || sizes.length < 2) { return }

  var docPreset = new DocumentPreset;
  docPreset.colorMode = DocumentColorSpace.RGB;
  docPreset.units = RulerUnits.Pixels;
  docPreset.width = sizes[0]
  docPreset.height = sizes[1]

  var doc = documents.addDocument('', docPreset);
  return doc
}

function saveDoc(dest) {
  testDest(dest)
  var doc = app.activeDocument
  var saveName = new File(dest);
  var saveOpts = new IllustratorSaveOptions();
  saveOpts.compatibility = Compatibility.ILLUSTRATOR24;
  saveOpts.saveMultipleArtboards = false;
  saveOpts.pdfCompatible = false;
  doc.saveAs(saveName, saveOpts );
}

function testDest(dest) {
  var path = dest.split('/')
  var fileName = path[path.length - 1]
  path.pop()
  var folder = path.join('/')
  var exportFolder = Folder(folder);
  if(!exportFolder.exists){
    exportFolder.create();
  }
}


/*
 *todo: 遇到csv文件中有双引号处理断行的文件，对当前行无法处理"
 */

function readFileLinesToList(sourceFile) {
  if (sourceFile == null) { return null }
  sourceFile.open("r", "*.csv", "????")
  sourceFile.lineFeed = "Windows"

  var currLine = sourceFile.readln()
  var keys = currLine.split(',')
  var datas = []
  while(currLine && currLine.split(',').join('') ) {
    var currLine = sourceFile.readln()
    var values = currLine.split(',')
    var currItem = {}
    for (var i = 0; i < keys.length; i++) {
      currItem[keys[i]] = values[i] && values[i].replace(/["|\r|\t|\s]/g, '')
    }
    datas.push(currItem)
  }
  sourceFile.close()
  return datas
}

/*
 * size: 'boardWidth*boardHeight'
 */
function putArtboard(info, order) {
  if (!info.size || app.documents.length < 1) { return }
  var sn = info.no ? (info.no.length < 2 ? '0' + info.no : info.no) : (order < 10 ? '0' + order : order)
  sn = sn ? sn + '-' : ''
  var medium = info.medium ? (info.medium + '-'): ''
  var position = info.position  ? info.position + '-' : ''
  var terminal = info.terminal  ? info.terminal + '-' : ''
  var capacity =  info.capacity ?  '-' + info.capacity : ''


  var size = info.size.match(/()\d+(\.\d+)?/g)
  if (!size || size.length < 2) { return }
	var artboards = app.activeDocument.artboards
	var artboardRect = artboards[artboards.getActiveArtboardIndex()].artboardRect

	// var x1 = (parseInt(artboardRect[2])) >> 0 // 起点为画板右边
  var GAP = 100
  var BOTTOM = -3000
  var x1, y1, x2, y2
  if (maxPoint[1] > BOTTOM) {
    x1 = (parseInt(artboardRect[0])) >> 0
    y1 = (parseInt(artboardRect[3]) - GAP) >> 0
    x2 = (parseInt(x1) + parseInt(size[0])) >> 0
    y2 = (y1 - size[1]) >> 0
  } else {
    x1 = maxPoint[0] + GAP * 8
    y1 = 7700 - 100 - 50
    x2 = (parseInt(x1) + parseInt(size[0])) >> 0
    y2 = y1 - size[1]
  }
  var rect = [x1, y1, x2, y2]
  maxPoint[0] = maxPoint[0] > x2 ? maxPoint[0] : x2
  maxPoint[1] = maxPoint[1] < y2 && maxPoint > BOTTOM ? maxPoint[1] : y2
  // maxPoint[0] = x2
  // maxPoint[1] = y2
  try {
    var artboard = artboards.add(rect);
    artboard.name = sn + medium + terminal + position + size.join('x') + 'px' + capacity
  } catch (e) {
    /* handle error */
    alert(e)
  }
}

/*
medium  terminal	position	format	size	capacity	title  subtitle	 promotion
网站     端口	     位置	      格式	   尺寸	  大小	    标题	  副标题	   促销政策
*/